package com.jiuzhe.commercial.main;

import android.app.Dialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.utils.RegexUtils;
import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.adapter.AuditAdapter;
import com.jiuzhe.commercial.base.BaseActivity;
import com.jiuzhe.commercial.bean.AuditInfoBean;
import com.jiuzhe.commercial.bean.MessageBean;
import com.jiuzhe.commercial.bean.UserBean;
import com.jiuzhe.commercial.constant.Constants;
import com.jiuzhe.commercial.http.CallBack;
import com.jiuzhe.commercial.http.HttpClient;
import com.jiuzhe.commercial.http.HttpClient2;
import com.jiuzhe.commercial.utils.SPUtil;
import com.jiuzhe.commercial.utils.UIUtils;
import com.jiuzhe.commercial.view.TimeButton;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 12078 on 2018/4/19.
 */

public class LoginActivity extends BaseActivity implements TextWatcher {

    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tbn_get_code)
    TimeButton tbnGetCode;
    @BindView(R.id.bt_login)
    Button btLogin;
    @BindView(R.id.bt_register)
    TextView btRegister;

    private String mPhone;
    private String mCode;
    private String rCode;
    private UserBean userBean = new UserBean();
    private UserBean.UserDtoBean userDto;
    private Dialog alertDialog;
    private String id;


    @Override
    protected void loadViewLayout() {
      //  atuoLogin();
        setContentView(R.layout.login_activity);
        setTitle("登录");
        setView(View.GONE);
    }

    private void atuoLogin() {
        HashMap<String, String> map = new HashMap<>();
        String token = SPUtil.getString(LoginActivity.this, Constants.TOKEN);
        id = SPUtil.getString(LoginActivity.this, Constants.ID);
        if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(token)) {
            map.put("id", id);
            String autoSignStr = Constants.AUTOLOGIN.substring(Constants.AUTOLOGIN.lastIndexOf("0/") + 1) + "?token=";
            String signStr = UIUtils.Md5(autoSignStr + token);
            map.put("token", id);
            map.put("sign", signStr);
            HttpClient.post(this, Constants.AUTOLOGIN, map, new CallBack<UserBean>() {
                @Override
                public void onSuccess(UserBean result) {
                    if (id.equals(result.getId())) {
                        SPUtil.put(LoginActivity.this, Constants.MERCHANTID, result.getUserDto().getMerchantId());
                        SPUtil.put(LoginActivity.this, Constants.TOKEN, result.getTaken());
                        UIUtils.startActivity(MainActivity.class);
                        finish();
                    }
                }
            });
        }
    }

    @Override
    protected void loadData() {
        mPhone = etPhone.getText().toString().trim();
        etPhone.addTextChangedListener(this);
    }


    @OnClick({R.id.bt_login, R.id.tbn_get_code, R.id.bt_register})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.bt_login:
                Login();
                break;

            case R.id.tbn_get_code:
                getCode();
                break;

            case R.id.bt_register:
                UIUtils.startActivity(RegisterActivity.class);
                Constants.PHONE = "";
                finish();
                break;
        }
    }

    /**
     * 登陆
     */
    private void Login() {
        String phone = etPhone.getText().toString().trim();
        mCode = etCode.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            UIUtils.showToastSafe("请输入手机号");
            return;
        } else if (!RegexUtils.isMobileExact(phone)) {
            Toast.makeText(this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(mCode)) {
            UIUtils.showToastSafe("请输入的短信验证码");
            return;
        } else if (mCode.length() == 6 && mCode.equals(rCode)) {

        } else {
            UIUtils.showToastSafe("请输入正确的短信验证码");
            return;
        }
        dialog.show();
        HashMap<String, String> map = new HashMap<>();
        map.put("id", userBean.getId());

        HttpClient.post(this, Constants.LOGIN, map, new CallBack<UserBean>() {
            @Override
            public void onSuccess(UserBean data) {
                if (data != null) {
                    dialog.dismiss();
                    userBean.setId(data.getId());
                    SPUtil.put(LoginActivity.this, Constants.ID, data.getId());
                    userBean.setUserDto(new UserBean.UserDtoBean());
                    userDto = data.getUserDto();
                    SPUtil.put(LoginActivity.this, Constants.MERCHANTID, data.getUserDto().getMerchantId());
                    SPUtil.put(LoginActivity.this, Constants.TOKEN, data.getTaken());
                    SPUtil.put(LoginActivity.this, Constants.REALNAME, userDto.getRealName());
                    SPUtil.put(LoginActivity.this, Constants.PHONE, userDto.getPhone());
                    userBean.setTaken(data.getTaken());
                    Constants.USERDTOBEAN = userDto;
                    if (data.getUserDto().getStauts() == 3) {  //关联的商户审核成功
                        UIUtils.startActivity(MainActivity.class);
                        finish();
                    } else if (data.getUserDto().getStauts() == 1) {
                        UIUtils.showToastSafe("您的帐户待审核，请稍后在试");
                        UIUtils.startActivity(MainActivity.class);
                        finish();
                        // audit();
                    } else if (data.getUserDto().getStauts() == 2) {
                        //  UIUtils.showToastSafe("您的帐户审核，请查看详情");
                        audit();
                    }
                }
            }

            @Override
            public void onFailure(int errorType, String message) {
                super.onFailure(errorType, message);
                dialog.dismiss();
            }
        });
    }

    /**
     * 审核失败，查看详情
     */
    private void audit() {
        HashMap<String, String> map = new HashMap<>();
        map.put("id", userBean.getId());
        HttpClient.get(this, Constants.AUDIT, map, new CallBack<List<AuditInfoBean>>() {
            @Override
            public void onSuccess(List<AuditInfoBean> result) {
                if (result != null && result.size() > 0) {
                    seeDetails(result);
                }
            }
        });
    }

    /**
     * 查看审核详情
     *
     * @param result
     */
    private void seeDetails(List<AuditInfoBean> result) {
        alertDialog = new Dialog(this, R.style.EasyListDialogStyle);
        mView = LayoutInflater.from(this).inflate(R.layout.dialog_audit, null);
        alertDialog.setContentView(mView);
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = this.getResources().getDisplayMetrics().widthPixels / 5 * 4;
        window.setAttributes(lp);
        RecyclerView rvAudit = alertDialog.findViewById(R.id.rv_audit);
        rvAudit.setLayoutManager(new LinearLayoutManager(this));
        //设置Item增加、移除动画
        rvAudit.setItemAnimator(new DefaultItemAnimator());
        AuditAdapter cityLeftAdapter = new AuditAdapter(result);
        rvAudit.setAdapter(cityLeftAdapter);
        Button btOk = alertDialog.findViewById(R.id.bt_ok);
        btOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                UIUtils.startActivity(RegisterActivity.class);
            }
        });
    }

    /**
     * 获得验证码
     */
    private void getCode() {
        int numcode = (int) ((Math.random() * 9 + 1) * 100000);
        rCode = String.valueOf(numcode);
        mCode = etCode.getText().toString().trim();
        HashMap<String, String> map = new HashMap<>();
        map.put("phone", etPhone.getText().toString().trim());
        map.put("messageCode", String.valueOf(numcode));

        HttpClient2.post(this, Constants.BOSS_PHONE_CODE, map, new CallBack<MessageBean>() {
            @Override
            public void onSuccess(MessageBean s) {
                if (s.getStatus().equals("0")) {
                    tbnGetCode.setEnabled(false);
                    UIUtils.showToastSafe("验证码已发送");
                    Constants.PHONE = "";
                    userBean.setId(s.getData().getId());
                //    etCode.setText(rCode);
                } else if (s.getStatus().equals("200105")) {
                    UIUtils.showToastSafe("您的手机号还未注册，请去注册帐号");
                    Constants.PHONE = "";
                    etPhone.setText("");
                    tbnGetCode.setText("获取验证码");
                    tbnGetCode.clearTimer();
                    tbnGetCode.setEnabled(true);
                } else if (s.getStatus().equals("200106")) {
                    UIUtils.showToastSafe("商户未审核");
                    tbnGetCode.setText("获取验证码");
                    tbnGetCode.clearTimer();
                }
            }
        });
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        Constants.PHONE = s.toString().trim();
        if (s.toString().trim().length() == 11) {
            SPUtil.put(this, Constants.User_Phone, s.toString().trim());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (tbnGetCode != null)
            tbnGetCode.onDestroy();
        if (alertDialog != null) {
            alertDialog = null;
        }
    }
}





